<template>
    <div class="app-container customer-div">
      <!--批量导入-->
      <el-dialog
        :show-close="showClose"
        :close-on-click-modal="showClose"
        :close-on-press-escape="showClose"
        :title="title"
        :beforeClose="beforeCloseEditPrice"
        :visible.sync="dialogVisibleImprot"
        width="500px">
        <div>
          <el-alert
            title="请先下载模板，维护后，再上传更新后的模板文件"
            type="warning"
            :closable="false">
          </el-alert>
          <div style="text-align: center;padding:20px;padding-bottom:10px">
            <el-link :href="url" type="primary" :underline="false"  v-if="type != 'importGoodsLineTarget'">下载模板</el-link>
          </div>
          <div class="upload-div">
            <input id="upload" type="file" @change="importfxx(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
            <el-button type="primary" size="small" :loading="uploadLoading">选择上传文件</el-button>
          </div>
          <div style="margin:20px auto;margin-bottom:0;word-break:break-all;text-align: left;line-height:20px;background: #fef0f0;color:#f56c6c;padding:10px" v-if="msg!=''">
            <div style="max-height: 90px;overflow: auto;padding:10px"><div v-if="showFial">添加失败：</div>{{msg}}</div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="handleEditPriceConfirm" :loading="EditLoading">提 交</el-button>
      </span>
      </el-dialog>
    </div>
</template>
<script>
    import {customerNewImportGoodLine,importMyGoodsLine} from '@/api/company'
    import XLSX from "xlsx";
    import { getToken } from '@/utils/auth'

    export default {
        name: "gtpop",
        data(){
            return {
              da:[],
              file:null,
              dialogVisibleImprot:false,//批量导入弹窗
              EditLoading:false,//批量导入提交按钮loadin
              showFial:false,//批量导入失败
              msg:'',//上传文件信息
              url:'',
              uploadLoading:false,
              showClose:true,
              title:'',
              type:'',
              token:'',
              fn:null
            }
        },
        computed: {

        },
        components : {

        },
        created() {

        },
        methods:{
          //显示批量导入弹窗
          showImport(type,title,url){
            this.showFial = false;
            this.EditLoading = false;
            this.uploadLoading = false;
            this.msg = '';
            this.type = type;
            this.title = title;
            this.token = getToken();
            this.url = url + '?token=' + this.token;
            this.dialogVisibleImprot = true;
            switch (type){
              case 'resourcelist':
                this.fn = customerNewImportGoodLine
                break;
              case 'importAllLine':
                this.fn = customerNewImportGoodLine;
                break;
              case 'importGoodsLineTarget':
                this.fn = importMyGoodsLine;
                break;
            }
          },
          //关闭批量导入弹窗
          beforeCloseEditPrice(){
            $("#upload").val('');
            this.da = [];
            this.msg = '';
            this.dialogVisibleImprot = false;
          },


          //提交批量导入
          handleEditPriceConfirm(){
            if (this.da.length == 0){
              this.$message({
                message: '上传数据为空',
                type: 'warning'
              });
              return false;
            }
            this.msg = '后台处理中，请耐心等待……';
            this.showFial = false;
            this.EditLoading = true;
            this.showClose = false;
            this.fn({list:this.da}).then((res)=>{
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.msg = '修改成功';
              this.EditLoading = false;
              this.dialogVisible = false;
              this.showClose = true;
              this.da = [];
              this.dialogVisibleImprot = false;
              $("#upload").val('');
              this.$emit('getList')
            }).catch((err)=>{
              this.msg = err.msg;
              this.showFial = true;
              this.EditLoading = false;
              $("#upload").val('');
              this.showClose = true;
            })
          },

          //导入excel
          importfxx(obj) {
            let _this = this;
            this.uploadLoading = true;
            let inputDOM = this.$refs.inputer;
            // 通过DOM取文件数据
            this.file = event.currentTarget.files[0];
            var rABS = false; //是否将文件读取为二进制字符串
            var f = this.file;
            var reader = new FileReader();
            //if (!FileReader.prototype.readAsBinaryString) {
            FileReader.prototype.readAsBinaryString = function(f) {
              var binary = "";
              var rABS = false; //是否将文件读取为二进制字符串
              var pt = this;
              var wb; //读取完成的数据
              var outdata;
              var reader = new FileReader();
              reader.onload = function(e) {
                var bytes = new Uint8Array(reader.result);
                var length = bytes.byteLength;
                for(var i = 0; i < length; i++) {
                  binary += String.fromCharCode(bytes[i]);
                }
                var XLSX = require('xlsx');
                if(rABS) {
                  wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
                    type: 'base64'
                  });
                } else {
                  wb = XLSX.read(binary, {
                    type: 'binary'
                  });
                }
                outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的东西
                // if (outdata.length  > 200){
                //   _this.$message({
                //     message: '最大上传200条',
                //     type: 'error'
                //   });
                //   var test = document.getElementById('upload');
                //   test.value = '';
                //   return false;
                // }
                _this.da = [...outdata];
                console.log("da",_this.da)
                let arr = [];

                let para = {
                  withList: arr
                };
                _this.$message({
                  message: '上传成功，请点击提交',
                  type: 'success'
                });
                _this.uploadLoading = false;
              };
              reader.readAsArrayBuffer(f);
            };
            if(rABS) {
              reader.readAsArrayBuffer(f);
            } else {
              reader.readAsBinaryString(f);
            }
          },

        },
    }
</script>

<style scoped lang="scss">
  .upload-div{
    text-align: center;
    position:relative;
    #upload{
      opacity: 0;
      position: absolute;
      z-index: 1;
      width:154px;
      height:40px
    }
  }
</style>
